use reqwest::Client;
use indicatif::{ProgressBar, ProgressStyle};
use std::path::Path;
use tokio::{fs::File, io::AsyncWriteExt};

pub async fn download_model(model: &str, dest: &Path) -> Result<(), DownloadError> {
    let config = crate::config::Config::load()?;
    let url = format!("{}{}/model.bin", config.repository_url, model);
    
    let client = Client::new();
    let response = client.get(&url)
        .send()
        .await?;

    let total_size = response.content_length().unwrap_or(0);
    let pb = ProgressBar::new(total_size);
    pb.set_style(ProgressStyle::default_bar()
        .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})")
        .unwrap());

    let mut file = File::create(dest).await?;
    let mut stream = response.bytes_stream();
    
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        file.write_all(&chunk).await?;
        pb.inc(chunk.len() as u64);
    }

    pb.finish_with_message("Download completed");
    Ok(())
}

#[derive(Debug, thiserror::Error)]
pub enum DownloadError {
    #[error("HTTP request failed: {0}")]
    Reqwest(#[from] reqwest::Error),
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    #[error("Configuration error: {0}")]
    Config(#[from] config::ConfigError),
}